package com.km.wskj.itmonitor.pager.monitor;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.AlarmList;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.alarm.AlarmDetailActivity;
import com.km.wskj.itmonitor.pager.monitor.alarm.AlarmStatisticsActivity;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;


/**
 * @author by Xianling.Zhou on 2017/2/9.
 */
//没有spinner的报警
public class AlarmListNoSpinnerActivity extends LActivity implements StateLayout.OnViewRefreshListener {

    private static final String TAG = "AlarmListNoSpinnerActiv";
    //ui
    @BindView(R.id.zlv_alarm_list)
    ZrcListView mZrcListView;
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right_text)
    TextView toolBarRightText;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;

    //data
    private int lastUpdateNum;
    private MyAdapter mAdapter;
    private int pageIndex;
    private List<AlarmList> alarmList = new ArrayList<>();
    private String deviceId;
    private String level1, level2, level3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_list_no_spinner);

        if (getIntent().hasExtra("id"))
            deviceId = getIntent().getStringExtra("id");
        ButterKnife.bind(this);

        toolBarBack.setVisibility(View.VISIBLE);
        toolBarTitle.setText("报警");
        toolBarRightText.setVisibility(View.VISIBLE);
        toolBarRightText.setText("统计");

        stateLayout.setRefreshListener(this);

        initData();
    }

    private void initData() {
        stateLayout.showLoadingView();
        pdc.alarmList(HTTP_TASK_TAG, deviceId, 1, Constant.PageListSize, -1, level1, level2, level3
                , new ZxlGenericsCallback<List<AlarmList>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                        stateLayout.showErrorView();
                    }

                    @Override
                    public void onResponse(List<AlarmList> alarmLists, int i) {
                        if (alarmLists.size() == 0)
                            stateLayout.showEmptyView();

                        alarmList = alarmLists;
                        lastUpdateNum = alarmLists.size();
                        pageIndex = 1;
                        //control
                        mAdapter.notifyDataSetChanged();
                        mZrcListView.setRefreshSuccess();

                        if (haveMore())
                            mZrcListView.startLoadMore();
                        else
                            mZrcListView.stopLoadMore();
                    }
                });
        initPullToRefresh();
    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#666666"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                AlarmList item = (AlarmList) parent.getItemAtPosition(position);
                Intent intent = new Intent(context, AlarmDetailActivity.class);
                intent.putExtra("id", item.id);
                startActivity(intent);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
        stateLayout.showContentView();
    }

    private void onRefresh() {
        pdc.alarmList(HTTP_TASK_TAG, deviceId, 1, Constant.PageListSize, -1, level1, level2, level3
                , new ZxlGenericsCallback<List<AlarmList>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        stateLayout.showErrorView();
                        LogUtils.e(TAG, e);
                    }

                    @Override
                    public void onResponse(List<AlarmList> alarmLists, int i) {
                        if (alarmLists.size() == 0)
                            stateLayout.showEmptyView();

                        alarmList = alarmLists;
                        lastUpdateNum = alarmLists.size();
                        pageIndex = 1;

                        //control
                        mAdapter.notifyDataSetChanged();
                        mZrcListView.setRefreshSuccess();

                        if (haveMore())
                            mZrcListView.startLoadMore();
                        else
                            mZrcListView.stopLoadMore();
                    }
                });

    }

    private void onLoadMore() {
        pdc.alarmList(HTTP_TASK_TAG, deviceId, pageIndex + 1, Constant.PageListSize, -1, level1, level2, level3
                , new ZxlGenericsCallback<List<AlarmList>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                    }

                    @Override
                    public void onResponse(List<AlarmList> alarmLists, int i) {
                        lastUpdateNum = alarmLists.size();
                        if (alarmLists.size() > 0) {
                            alarmList.addAll(alarmLists);
                            pageIndex++;
                        }

                        //control
                        mAdapter.notifyDataSetChanged();
                        mZrcListView.setLoadMoreSuccess();
                        if (haveMore())
                            mZrcListView.startLoadMore();
                        else
                            mZrcListView.stopLoadMore();
                    }
                });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    //点击事件
    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right_text:
                openIntent(AlarmStatisticsActivity.class, true);
                break;
        }
    }

    @Override
    public void refreshClick() {
        initData();
    }

    @Override
    public void loginClick() {

    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (alarmList == null) {
                return 0;
            }
            return alarmList.size();
        }

        @Override
        public Object getItem(int position) {
            AlarmList item = alarmList.get(position);
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent
                    , R.layout.alarm_list_item);
            AlarmList item = alarmList.get(position);
            helper.setText(R.id.alarm_item_deviceName, item.deviceName);
            helper.setText(R.id.alarm_item_message, item.message);
            helper.setTag(R.id.alarm_item_createTime, item.createTime);

            //运行状态//状态 0 未处理 1 已处理
            switch (item.status) {
                case 0:
                    helper.setText(R.id.alarm_item_status, "未处理");
                    helper.setBackgroundColor(R.id.alarm_item_status, Color.parseColor("#ed7d31"));
                    break;

                case 1:
                    helper.setText(R.id.alarm_item_status, "已处理");
                    helper.setBackgroundColor(R.id.alarm_item_status, Color.parseColor("#70ad47"));
                    break;

            }
            return helper.getView();
        }
    }

}
